﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using MDT.LifeSewagePlatform.Entity;
using MDT.LifeSewagePlatform.IRepository;
using Microsoft.EntityFrameworkCore;

namespace MDT.LifeSewagePlatform.Repository
{
    public class UserRepository: HandleBaseRepository<UserEntity>,IUserRepository
    {
        public UserRepository()
        {

        }
        public IQueryable<UserView> GetUsers(Expression<Func<UserView,bool>> expression)
        {
            var query = from user in _dbContext.Users.AsNoTracking()
                        join role in _dbContext.Roles.AsNoTracking() on user.RoleID equals role.ID
                        join company in _dbContext.Company.AsNoTracking() on user.CompanyID equals company.ID
                        join place in _dbContext.Details.AsNoTracking() on company.PlaceTypeID equals place.ID
                        join Pro in _dbContext.Regions.AsNoTracking() on company.ProvinceID equals Pro.ID
                        join city in _dbContext.Regions.AsNoTracking() on company.CityID equals city.ID
                        join area in _dbContext.Regions.AsNoTracking() on company.AreaID equals area.ID
                        join cuarea in _dbContext.Regions.AsNoTracking() on user.CurrentAreaID equals cuarea.ID into Leftareacurrent
                        from currentArea in Leftareacurrent.DefaultIfEmpty()
                        select new UserView
                        {
                            UserName = user.UserName,
                            Phone = user.PhoneNumber,
                            CityID = city.ID,
                            CityName = city.DisplayName,
                            ProvinceID = Pro.ID,
                            ProvinceName = Pro.DisplayName,
                            AreaID = area.ID,
                            AreaName = area.DisplayName,
                            ID = user.ID,
                            RoleName = role.RoleName,
                            UserPassword = user.UserPassword,
                            Email = user.Email,
                            IsDelete = user.IsDelete,
                            RoleValue = role.RoleValue,
                            PlaceTypeID = place.ID,
                            CompanyID = company.ID,
                            CompanyName = company.CompanyName,
                            PlaceTypeName = place.RowName,
                            CurrentAreaId=user.CurrentAreaID,
                            RoleID=role.ID,
                            DisplayRoleName=role.DisplayName,
                            CurrentAreaName=currentArea==null?"无":currentArea.DisplayName
                        };

            return query.Where(expression);
        }
    }
}
